//
//  UpdateInfoManager.m
//  ebook
//
//  Created by 吴超飞 on 16/10/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "UpdateInfoManager.h"
#import "Book.h"

@interface UpdateInfoManager(){
    NSMutableArray *lastUpdatebooks;
    NSString *lastInfo;
}

@end

@implementation UpdateInfoManager

+(instancetype)shareInstance{
    
    static UpdateInfoManager *model = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        model = [[UpdateInfoManager alloc] init];
    });
    return model;
}

-(void)showUpdateInfo:(NSArray *)books inView:(UIView *)view{
    
    NSMutableArray *updateArray = [NSMutableArray array];//有更新的书籍列表
    for (Book *book in books) {
        if([book.chaptercount intValue]>[book.lasthaptercount intValue]){
            [updateArray addObject:book];
        }
    }
    
    NSString *info;
    if(![self isNil:updateArray]){//更新列表不为空
        if (![self newArray:updateArray isSubsetOfOldarray:lastUpdatebooks]) {//且不是原更新提示的自己
            info = [self updateinfoOfBooks:updateArray];
            lastUpdatebooks = updateArray;
        }
    }else{
        info=@"您追看的小说暂无更新";
    }
    
    if(info&&![info isEqualToString:lastInfo]){
        [ToastView showMsg:info inView:view isCenter:NO];
        lastInfo = info;
    }
}

-(BOOL)newArray:(NSMutableArray *)newArrary isSubsetOfOldarray:(NSMutableArray *)oldArrary{
    
    BOOL issub = YES;
    for (Book *nbook in newArrary) {
        BOOL hasexist = NO;
        for (Book *obook in oldArrary) {
            if([nbook.bookid intValue]==[obook.bookid intValue]&&[nbook.chaptercount intValue]==[obook.chaptercount intValue]&&[nbook.lasthaptercount intValue]==[obook.lasthaptercount intValue]){
                hasexist = YES;
                break;
            }
        }
        if(!hasexist){//有一项不在原数组中则不是全子集
            issub=NO;
            break;
        }
    }
    
    return issub;
}

-(BOOL)isNil:(NSArray*)array{
    return (!array||array.count==0);
}

//由更新书籍列表构建更新消息
-(NSString *)updateinfoOfBooks:(NSMutableArray*)books{
    
    NSString *info=nil;
    int count = 0;
    int totoalChapters = 0;
    NSString *bookName;
    for (Book *book in books) {
        if([book.chaptercount intValue]>[book.lasthaptercount intValue]){
            count++;
            totoalChapters+=[book.chaptercount intValue]-[book.lasthaptercount intValue];
            if(!bookName)bookName=book.bookname;
        }
    }
    if(count>0){
        info=[NSString stringWithFormat:@"《%@》等共%d本书共更新了%d章",bookName,count,totoalChapters];
    }
    
    return info;
}

@end
